<?php
/**
 * Created by PhpStorm.
 * User: zgh
 * Date: 2021-08-05
 * Time: 14:45
 */

namespace app\admin\service;

use app\admin\item\ItemLoader;
use app\admin\pipeline\ItemAdapter;
use app\admin\validate\AdvValidate;
use app\common\model\AdvModel;

class AdvService
{


    public static function getByID($id)
    {
        $adapter = new  ItemAdapter(AdvModel::class);
        return $adapter->id($id)->getModel();
    }

    public static function getList($params)
    {
        $pagination = filter_pagination(@$params['page'], @$params['limit']);
        $loader = new ItemLoader();
        $where = $loader->addVal($params)->addWhere(['status', '<>', -1])
            ->addWhereSearch("title", "str", true)
            ->addWhereSearch("type", "int", false)
            ->loadWhere();
        $query = AdvModel::where($where)->order(["weight" => "desc", "id" => "desc"]);
        $data['total'] = $query->count();
        $data['dataList'] = [];
        if ($data['total']) {
            $data['dataList'] = $query->limit($pagination['start'], $pagination['limit'])->select()->toArray();
        }
        return $data;
    }


    public static function save($params)
    {
        $loader = new ItemLoader();
        $data = $loader->addVal($params)->addVerify(AdvValidate::class)->loadItem();
        $adapter = new ItemAdapter(AdvModel::class);
        $res = $adapter->save($data);
        if ($res) {
            return $adapter->getId();
        } else {
            return false;
        }
    }


    public static function del($params)
    {
        $adapter = new ItemAdapter(AdvModel::class);
        return $adapter->whereUpdate([["id", "in", $params['id']]], ["status" => -1]);
    }
}